#!/bin/sh

################################################################################
# Copyright 1999-2010 by Nice, srl.,
# Via Milliavacca, 9
# 14100 Asti (AT) - ITALY
# All rights reserved.
#
# This software is the confidential and proprietary information
# of Nice, srl. ("Confidential Information").
# You shall not disclose such Confidential Information
# and shall use it only in accordance with the terms of
# the license agreement you entered into with Nice.
################################################################################

#------------------------------------------------------------------
# Rename a file or directory
#
# Usage: fm.rename <path> <old_name> <new_name>
#
# - path:     the current path (relative to vroot)
# - old_name: the current name of the file/directory
# - new_name: the new name
#
#------------------------------------------------------------------

. "${EF_ROOT}/plugins/irods/bin/common"
. "${EF_ROOT}/plugins/fm/fm/backends/common"

if [ -z "$1" ]; then
  fatal "Cannot rename item" "Missing input parameter: current path"
fi

if [ -z "$2" ]; then
  fatal "Cannot rename item" "Missing input parameter: file/directory to rename"
fi

if [ -z "$3" ]; then
  fatal "Cannot rename item" "Missing input parameter: new name"
fi

#printf "$2" | grep "/" >/dev/null 2>&1 
#if [ $? -eq 0 ]; then
#  fatal "Cannot rename \"$2\"" "Invalid input parameter: \"$2\" is not a valid filename"
#fi

printf "$3" | grep "/" >/dev/null 2>&1 
if [ $? -eq 0 ]; then
  error "Cannot rename \"$2\" to \"$3\"" "Slashes are not allowed in filenames. Please use a different name."
fi

if [ "$2" = "$3" ]; then
  exit 0
fi

#_fullpath="${FM_VROOT_PATH}$1"
_fullpath="${1}"

# Change to the required directory
${IRODS_ICOMMANDS_DIR}/icd "${_fullpath}" >/dev/null 2>&1
if [ $? -ne 0 ]; then
    fatal "Cannot rename \"$2\" to \"$3\"" "Cannot access to working directory"
fi

#if [ -e "$3" ]; then
#    error "Cannot rename \"$2\" to \"$3\"" "The name \"$3\" is already used in this directory. Please use a different name."
#fi

from="${1}/${2}"

to="${1}/${3}"

_message="`${IRODS_ICOMMANDS_DIR}/imv \"${from}\" \"${to}\" 2>&1`"
if [ $? -ne 0 ]; then
  # FIXME: it would be nice to report the actual error message to users in a portable way
  _message="`echo \"${_message}\" | cut -d: -f3`"
  error "Cannot rename \"${from}\" to \"${to}\"" "`trim ${_message}`"
fi

